import { childrenProps, BasicForm, FormKeys } from '@/components/ProForm/interface/index';
import { PublicInterface } from '@/interface/public';

import { defaultStyle } from '@/basic/style';
import { DeptInterface } from '@/api/interface/dept/dept';
import { deptSave } from '@/api/modules/dept/dept';
import { RosterInterface } from '@/api/interface/personnel/roster/roster';

export function useDeptForm(proTableBox: PublicInterface.ProTableValue) {
  let deptForm = reactive<BasicForm<DeptInterface.ReqSave>>({
    form: {
      id: null,
      name: '',
      pid: null,
      managerId: null,
      sort: null,
      remark: ''
    },
    title: '',
    visible: false,
    options: [
      {
        label: 'id',
        prop: 'id',
        hide: true,
        type: 'input',
        defaultValue: ''
      },
      {
        type: 'input',
        label: '部门名称',
        hide: false,
        prop: 'name',
        defaultValue: '',
        rules: [{ required: true, message: '部门名称', trigger: 'blur' }]
      },

      {
        type: 'select',
        label: '部门负责人',
        hide: false,
        defaultValue: [],
        prop: 'managerId',

        rules: [{ required: true, message: '部门名称', trigger: 'blur' }]
      },
      {
        type: 'select',
        label: '所属上级',
        hide: false,
        defaultValue: 0,
        prop: 'pid',
        children: [],
        attrs: {
          clearable: true
        }
      },
      {
        type: 'input',
        label: '排序',
        hide: false,
        prop: 'sort',
        defaultValue: ''
      },
      {
        type: 'input',
        label: 'remark',
        defaultValue: '',
        hide: false,
        prop: 'remark',
        attrs: {
          style: defaultStyle
        }
      }
    ]
  });

  const saveAddDeptForm = async (form: DeptInterface.ReqSave) => {
    form.pid = !form.pid ? 0 : form.pid;
    await deptSave(form);
    deptForm.visible = false;
    elMessage();
    proTableBox.value?.getTableList();
  };

  /**
   * 获取表单中的选择数据
   */
  const getAddDeptFormChildren = async () => {
    const rosterPageParams: RosterInterface.ReqRosterPageList = {
      pageNum: 1,
      pageSize: 10000,
      status: [1],
      queryType: 'NORMAL'
    };
    const res = await promiseAllApi([rosterPageList(rosterPageParams), deptListByFlattenTree({ status: BasicKey.ENABLE })]);

    const children: Map<FormKeys<DeptInterface.ReqSave>, childrenProps[]> = new Map();
    children.set('managerId', arrTransitionTreeData<any>(res[0].records, 'name', 'id'));
    children.set('pid', arrTransitionTreeData<any>(res[1], 'name', 'id'));
    formSetChildren(deptForm, children);
  };

  return { deptForm, saveAddDeptForm, getAddDeptFormChildren };
}
